package com.yulongtian.domain;

import com.alibaba.fastjson.annotation.JSONField;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author yulongTian
 * @create 2022-10-29 16:47
 */
@Data
@NoArgsConstructor
public class LoginUser implements UserDetails {

    private User user;

    private List<String> permission;

    //不让他序列化  否则存入redis中会报错
    @JSONField(serialize = false)
//            存储springsecurity所需要的权限信息的集合
    List<SimpleGrantedAuthority> authorities;

    public LoginUser(User user, List<String> permission) {
        this.user = user;
        this.permission = permission;
    }

    //返回权限信息
    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        //把permission中的String类型的权限信息封装成 SimpleGrantedAuthority 对象
//        List<GrantedAuthority> newList=new ArrayList<>();
//            for (String perm : permission) {
//                SimpleGrantedAuthority authority = new SimpleGrantedAuthority(perm);
//                newList.add(authority);
//            }

        //只转换一次
        if (authorities != null) {
            return authorities;
        }
//        String流函数式编程方法实现
        authorities = permission
                .stream()
                .map(SimpleGrantedAuthority::new)
                .collect(Collectors.toList());
        return authorities;
    }

    //    获取密码
    @Override
    public String getPassword() {
        return user.getPassword();
    }

    //获取用户名
    @Override
    public String getUsername() {
        return user.getUserName();
    }

    //判断是否没过期
    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    //是否没有锁定
    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    //是否没有超时
    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    //是否可用
    @Override
    public boolean isEnabled() {
        return true;
    }
}
